package com.le.medium.class6;

import org.junit.Test;

import java.util.TreeMap;

/**
 * 给你一个字符串类型的数组 arr，譬如： String[] arr = { "b\\cst", "d\\", "a\\d\\e", "a\\b\\c" };
 * 你把这些路径中蕴含的目录结构给画出来，子目录直接列在父目录下面，并比父目录 向右进两格，就像这样:
 * a
 *      b
 *          c
 *      d   e
 * b    cst
 * d
 * 同一级的需要按字母顺序排列，不能乱。
 * 思路：
 *  构建字典树，外加打印
 */
public class Problem01_GetFolderTree {

    public static class Node{
        String name;
        TreeMap<String,Node> nextMap;

        public Node(String name) {
            this.name = name;
            this.nextMap =  new TreeMap<>();
        }
    }

    public static void printArray(String[] arr){
        if (arr == null || arr.length == 0){
            return;
        }
        Node head = generateFolderTree(arr); // 构建字典树
        printProcess(head, 0); // 打印
    }

    // 构建字典树
    private static Node generateFolderTree(String[] folderPaths) {
        // 新建根节点
        Node head = new Node("");
        for (String folderPath : folderPaths) {
            // b\\cst --> [b ,cst]
            String[] paths = folderPath.split("\\\\");
            Node cur = head;
            for (String path : paths) {
                // 如果不包含当前path,则新建
                if (!cur.nextMap.containsKey(path)){
                    cur.nextMap.put(path,new Node(path));
                }
                // 指针下移
                cur = cur.nextMap.get(path);
            }
        }
        return head;
    }

    public  static void printProcess(Node head, int level){
        if (level != 0) {
            System.out.println(get2nSpace(level) + head.name);
        }
        for (Node next : head.nextMap.values()) {
            printProcess(next, level + 1);
        }
    }
    public static String get2nSpace(int n) {
        String res = "";
        for (int i = 1; i < n; i++) {
            res += "  ";
        }
        return res;
    }

    @Test
    public void test(){
        String[] arr = { "b\\cst", "d\\", "a\\d\\e", "a\\b\\c" };
        printArray(arr);
    }
}
